package util

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"mbti/Global"

	"os"
)

// 这里要改成你的mod包名

func InitDB(v *viper.Viper) (db *gorm.DB, erre error) {
	var err error
	dsn := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
		v.GetString("datasource.username"),
		v.GetString("datasource.password"),
		v.GetString("datasource.database"),
		v.GetString("datasource.host"),
		v.GetString("datasource.port"),
	)
	db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败" + err.Error())
		return db, erre
	}

	fmt.Println("数据库连接成功")
	//err = db.AutoMigrate(&model.Students{})
	if err != nil {
		return nil, err
	}
	return db, erre

}

func InitRedisDB(v *viper.Viper) (conn redis.Conn, err error) {
	db, err := redis.Dial("tcp", v.GetString("redis.host")+":"+v.GetString("redis.port"))
	if err != nil {
		fmt.Println("连接redis失败！, ", err.Error())
		Global.Flag = false
		return
	}
	fmt.Println("redis连接成功")
	Global.Flag = true
	return db, err
}

func Test(db *gorm.DB) {
	fmt.Println("进入Test函数")
	//db.AutoMigrate(&model.Students{})
	//a := &model.Students{
	//	SID:        "2020",
	//	SNAME:      "Nana",
	//	SSEX:       "beauty",
	//	CLASS_NAME: "01",
	//	S_PASSWORD: "123456",
	//}
	//
	//result := db.Create(a)
	//fmt.Println("result = ", result)
	//log.Println(a.SID)
	//log.Println(result.Error)
	//log.Println(result.RowsAffected)

	return

}

// InitConfig 初始化配置文件的函数
func InitConfig() (v *viper.Viper) {
	workDir, _ := os.Getwd()
	v = viper.New()
	v.SetConfigName("application")
	v.SetConfigType("yml")
	v.AddConfigPath(workDir + "/config")
	err := v.ReadInConfig()
	if err != nil {
		fmt.Printf("读取配置文件出错:%s\n", err)
	}
	return v
}
